package com.sphd.restaurantsystem.activitys.funding;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.activitys.ForgetPasswordActivity;
import com.sphd.restaurantsystem.activitys.MyselfSettingActivity;
import com.sphd.restaurantsystem.activitys.SettingActivity;
import com.sphd.restaurantsystem.activitys.ShareEwmActivity;
import com.sphd.restaurantsystem.activitys.UserHomeActivity;
import com.sphd.restaurantsystem.adapters.FundingPersonAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.InvestRuleInfo;
import com.sphd.restaurantsystem.info.InvestorInfo;
import com.sphd.restaurantsystem.info.InvestorItemInfo;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.presenter.FundingPersonPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.FundingPersonView;
import com.wzh.frame.utils.BigDisMailUtils;
import com.wzh.frame.utils.StringUtils;
import com.wzh.frame.utils.TimeUtils;
import com.wzh.frame.views.RoundImageView;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 投资者界面
 */
public class FundingPersonageActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, FundingPersonView {

    @BindView(R.id.menu_request_record)
    TextView menuRequestRecord;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.btn_in)
    Button btnIn;
    @BindView(R.id.btn_out)
    Button btnOut;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    Intent intent;
    private View headerView;
    private LinearLayout headLayout;
    private RoundImageView roundView;
    private TextView userName, userPermission, managerNav, goRestaurantNav, addRestaurantNav, myFuding, crowdfundingmanger;
    private TextView m_today_cut, m_account_money, m_year_cut_money, m_cut_money;
    LoginInfo loginInfo;
    RestaurantInfo restaurantInfo;
    Bundle bundle;
    FundingPersonPresenterImpl fundingPersonPresenter;
    FundingPersonAdapter fundingPersonAdapter;
    List<InvestorItemInfo> investorItemInfos;
    View headView;
    InvestorInfo investorInfo;
    double limit = 0;
    long account_floor_day;
    TextView deal;
    double permillage;
    String manName, manPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funding_personage);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        m_account_money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfo);
                bundle.putSerializable(Constant.INVESTOR, investorInfo);
                intent.putExtras(bundle);
                intent.putExtra(Constant.TAG, FundingPersonageActivity.class.getSimpleName());
                intent.setClass(context, MoneyRecordActivity.class);
                startActivity(intent);
            }
        });

        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                bundle.putSerializable(Constant.INVESTOR, investorInfo);
                bundle.putSerializable(Constant.INVESTORITEM, (InvestorItemInfo) baseQuickAdapter.getItem(i));
                intent.putExtras(bundle);
                intent.setClass(context, MonthDetailsActivity.class);
                startActivity(intent);
            }
        });

        deal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InvestRuleInfo investRuleInfo = new InvestRuleInfo();
                investRuleInfo.setAccount_permillage(permillage);
                investRuleInfo.setAccount_floor_day((int) account_floor_day);
                bundle.putSerializable(Constant.INVESTOR, investorInfo);
                bundle.putSerializable(Constant.INVESTRULE, investRuleInfo);
                bundle.putString(Constant.manName, manName);
                bundle.putString(Constant.manPhone, manPhone);
                intent.putExtras(bundle);
                intent.setClass(context, DealActivity.class);
                startActivity(intent);
            }
        });
        headLayout.setOnClickListener(v -> {
            intent.setClass(context, MyselfSettingActivity.class);
            startActivity(intent);
        });
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        headerView = navView.getHeaderView(0);
        loginInfo = DataSupport.findLast(LoginInfo.class);
        setTitleBar(toolbar,loginInfo.getStaff_name());
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navView.setNavigationItemSelectedListener(this);
        fundingPersonPresenter = new FundingPersonPresenterImpl(this);

        initHeader();
        initAdapter();
        initHeadView();
        addData();
    }

    private void initHeadView() {
        headerView = getView(R.layout.head_view_funding_person);
        m_today_cut = $(R.id.m_today_cut, headerView);
        m_account_money = $(R.id.m_account_money, headerView);
        m_year_cut_money = $(R.id.m_year_cut_money, headerView);
        m_cut_money = $(R.id.m_cut_money, headerView);
        fundingPersonAdapter.addHeaderView(headerView);
    }

    private void addData() {
        fundingPersonPresenter.getData(RestaurantUrl.Httptitle + RestaurantUrl.PERSONACCOUNT + "cgid=" + restaurantInfo.getId() +
                "&phone=" + loginInfo.getStaff_phone(), restaurantInfo);
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecy);
        investorItemInfos = new ArrayList<>();
        fundingPersonAdapter = new FundingPersonAdapter(R.layout.item_accout_details, investorItemInfos);
        myRecy.setAdapter(fundingPersonAdapter);


    }

    private void initHeader() {
        headLayout = (LinearLayout) headerView.findViewById(R.id.nav_head_linear);
        roundView = (RoundImageView) headerView.findViewById(R.id.imageView_title);
        userName = (TextView) headerView.findViewById(R.id.username_textview);
        userPermission = (TextView) headerView.findViewById(R.id.permissions_textview);
        deal = (TextView) headerView.findViewById(R.id.deal);

        setImage(roundView, loginInfo.getStaff_photo());
        userName.setText(loginInfo.getStaff_name());
        userPermission.setText(loginInfo.getStaff_auth() == 2 ? "超管" : loginInfo.getStaff_auth() == 3 ? "店长" : loginInfo.getStaff_auth() == 4 ? "接单员" : loginInfo.getStaff_auth() == 5 ? "服务员" : "投资人");
    }


    @Override
    public void onBackPressed() {

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_see://查看店铺信息
                intent.setClass(context, UserHomeActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_changepassword://修改密码界面
                intent.setClass(context, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_share://二维码分享界面包括管理端和用户端
                intent.setClass(context, ShareEwmActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_about://关于中心
                intent.setClass(context, SettingActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @OnClick({R.id.btn_in, R.id.btn_out})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_in:
                showUpDialog(1, "请输入追加金额");
                break;
            case R.id.btn_out:
                new GetTimeTask().execute("");
                break;
        }
    }

    /**
     * 跳转到申请记录界面
     */
    @OnClick(R.id.menu_request_record)
    public void onClick() {
        bundle.putInt(Constant.TYPE, 3);
        InvestRuleInfo investRuleInfo = new InvestRuleInfo();
        investRuleInfo.setAccount_permillage(permillage);
        investRuleInfo.setAccount_floor_day((int) account_floor_day);
        bundle.putSerializable(Constant.INVESTRULE, investRuleInfo);
        bundle.putSerializable(Constant.RESTAURANTSINFO, restaurantInfo);
        intent.putExtras(bundle);
        intent.setClass(context, ApplyForActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }


    class GetTimeTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            return getWebsiteDatetime("http://www.baidu.com");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("1")) {
                showUpDialog(0, "最高可撤回金额" + turn(limit, 2));
            } else {
                toast("投资期内,不可撤回。");
            }
        }
    }

    private String getWebsiteDatetime(String webUrl) {
        try {
            URL url = new URL(webUrl);// 取得资源对象
            URLConnection uc = url.openConnection();// 生成连接对象
            uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
            long day = (timeFormat(ld) - timeFormat(TimeUtils.stringToLong(investorInfo.getAccount_regtime(), TimeUtils.STRING_DATE_FORMAT_DATE))) / (24 * 60 * 60 * 1000);
            if (account_floor_day <= day) {
                return "1";
            } else {
                return "0";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private long timeFormat(long time) {

        String formatTime = TimeUtils.getTime(time, TimeUtils.DATE_FORMAT_DATE);
        try {
            Log.e("22==", TimeUtils.stringToLong(formatTime, TimeUtils.STRING_DATE_FORMAT_DATE) + "");
            return TimeUtils.stringToLong(formatTime, TimeUtils.STRING_DATE_FORMAT_DATE);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void showUpDialog(int type, String msg) {
        View view = getView(R.layout.dialog_add);
        TextView mAccountMoney = (TextView) view.findViewById(R.id.m_account_money);
        final EditText mAddMoney = (EditText) view.findViewById(R.id.m_add_money);
        mAddMoney.setHint(msg);
        Button mSave = (Button) view.findViewById(R.id.m_save);
        Button mCancle = (Button) view.findViewById(R.id.m_cancle);
        mAccountMoney.setText(BigDisMailUtils.turnTrim(investorInfo.getInvestment(), Constant.DECIMAL_POINT));
        final AlertDialog alertDialog = new AlertDialog.Builder(this).setView(view).create();
        alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        alertDialog.show();
        mSave.setOnClickListener(v -> {
            if (isNoHeard(mAddMoney.getText().toString().trim())) {
                if (type == 0) {
                    if (TextUtils.isEmpty(mAddMoney.getText().toString())) {
                        toast("撤回金额不能为空");
                    } else if (Double.parseDouble(mAddMoney.getText().toString()) == 0) {
                        toast("撤回金额不能为0");
                    } else if (Double.parseDouble(mAddMoney.getText().toString()) >
                            limit) {
                        toast("撤回金额不能大于可撤回金额，请重新输入");
                    } else if (!isNoHeard(mAddMoney.getText().toString())) {
                        toast("请输入正确的金额");
                    } else {
                        updateMoney(type, alertDialog, mAddMoney.getText().toString(), investorInfo.getInvestment());

                    }
                } else {
                    if (TextUtils.isEmpty(mAddMoney.getText().toString())) {
                        toast("投资金额不能为空");
                    } else if (Double.parseDouble(mAddMoney.getText().toString()) == 0) {
                        toast("投资金额不能为0");
                    } else if (!isNoHeard(mAddMoney.getText().toString())) {
                        toast("请输入正确的金额");
                    } else {
                        updateMoney(type, alertDialog, mAddMoney.getText().toString(), investorInfo.getInvestment());
                    }

                }
            } else {
                toast("请输入正确的金额");
            }

        });
        mCancle.setOnClickListener(v -> {
            alertDialog.dismiss();
        });
    }

    private void updateMoney(int type, final AlertDialog alertDialog, String inoroutMoney, double allMoney) {
        fundingPersonPresenter.setAddOrCut(RestaurantUrl.Httptitle + RestaurantUrl.MONEYUPDATE +
                "cgid=" + restaurantInfo.getId() + "&name=" + StringUtils.utf8Encode(loginInfo.getStaff_name()) +
                "&money=" + inoroutMoney + "&phone=" +
                loginInfo.getStaff_phone() + "&staffid=" + investorInfo.getAccount_staffid() + "&type=" + type +
                "&sum_account=" + allMoney, alertDialog);
    }

    @Override
    public void recAddOrCut(int res, AlertDialog alertDialog) {
        if (res == 1) {
            toast("操作已成功");
        } else {
            toast("操作失败，请重试！");
        }
        alertDialog.dismiss();
        addData();
    }

    @Override
    public void manPhone(String staff_phone) {
        this.manPhone = staff_phone;
    }

    @Override
    public void manName(String staff_name) {
        this.manName = staff_name;
    }

    @Override
    public void senditemInfoList(List<InvestorItemInfo> itemInfoList) {
        fundingPersonAdapter.setNewData(itemInfoList);
    }

    @Override
    public void limit(double limit) {
        this.limit = limit;
    }

    @Override
    public void allInterest(double all_interest) {
        m_cut_money.setText(BigDisMailUtils.turnTrim(all_interest, Constant.DECIMAL_POINT_TWO));
    }

    @Override
    public void permillage(double permillage) {
        this.permillage = permillage;
    }

    @Override
    public void todayMoney(double today) {
        m_today_cut.setText(BigDisMailUtils.turnTrim(today, Constant.DECIMAL_POINT_TWO));
    }

    @Override
    public void floorDay(long account_floor_day) {
        this.account_floor_day = account_floor_day;
    }

    @Override
    public void sendPerseonMsg(List<InvestorInfo> infoList) {
        if (infoList.size() != 0) {
            investorInfo = infoList.get(0);
            m_account_money.setText(BigDisMailUtils.turnTrim(infoList.get(0).getInvestment(), Constant.DECIMAL_POINT_TWO));
            m_year_cut_money.setText(BigDisMailUtils.turnTrim(infoList.get(0).getInterest(), Constant.DECIMAL_POINT_TWO));
        }
    }

    @Override
    public void sendResInfo(RestaurantInfo restaurantInfo) {
        this.restaurantInfo = restaurantInfo;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            addData();
        }
    }
}
